package com.qunar.wan.util;

import com.google.common.base.Preconditions;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringEscapeUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by hiCyoung on 13-12-1.
 * <p/>
 * Title: HTML相关的正则表达式工具类
 * Description: 包括过滤HTML标记，转换HTML标记，替换特定HTML标记
 */
public class HTMLTagsUtil {
    private HTMLTagsUtil() {
    }

    private static final Pattern P_BLANKSPACE = Pattern.compile("\\s*|\t|\r|\n", Pattern.CASE_INSENSITIVE);
    private static final Pattern P_SCRIPT = Pattern.compile("<script[^>]*?>[\\s\\S]*?<\\/script>", Pattern.CASE_INSENSITIVE);
    private static final Pattern P_STYLE = Pattern.compile("<style[^>]*?>[\\s\\S]*?<\\/style>", Pattern.CASE_INSENSITIVE);
    private static final Pattern P_HTML = Pattern.compile("<[^>]+>");


    /**
     * 通过正则去除HTML标记
     *
     * @param htmlStr
     * @return
     */
    public static String delHTMLTag(String htmlStr) {
        Preconditions.checkArgument(htmlStr != null, "参数不能为空");

        Matcher m = P_BLANKSPACE.matcher(htmlStr);
        htmlStr = m.replaceAll("");

        Matcher script = P_SCRIPT.matcher(htmlStr);
        htmlStr = script.replaceAll(""); // 过滤script标签

        Matcher style = P_STYLE.matcher(htmlStr);
        htmlStr = style.replaceAll(""); // 过滤style标签

        Matcher html = P_HTML.matcher(htmlStr);
        htmlStr = html.replaceAll(""); // 过滤html标签

        return htmlStr.trim(); // 返回文本字符串
    }

    /**
     * 转义标记以正常显示
     *
     * @param input
     * @return String
     */
    public static String replaceTag(String input) {
        StringBuilder filtered = new StringBuilder(input.length());
        char c;
        for (int i = 0; i <= input.length() - 1; i++) {
            c = input.charAt(i);
            switch (c) {
                case '<':
                    filtered.append("&lt;");
                    break;
                case '>':
                    filtered.append("&gt;");
                    break;
                case '"':
                    filtered.append("&quot;");
                    break;
                case '&':
                    filtered.append("&amp;");
                    break;
                default:
                    filtered.append(c);
            }
        }
        return (filtered.toString());
    }

    /**
     * 转义HTML标签，可以自定义不许要转义的标签
     *
     * @param input
     * @param excludeTags 自定义不需要转义的标签
     * @return
     */
    public static String escapeHtml(String input, String[] excludeTags) {
        String escapeStr = StringEscapeUtils.escapeHtml4(input);
        if (ArrayUtils.isEmpty(excludeTags)) {
            return escapeStr;
        }
        for (String excludeTag : excludeTags) {
            escapeStr = escapeStr.replaceAll(Pattern.quote(StringEscapeUtils.escapeHtml4(excludeTag)), excludeTag);
        }
        return escapeStr;
    }

}
